package com.qs.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.qrcode.encoder.QRCode;
import com.qs.constant.StatusConstant;
import com.qs.exception.ServiceException;
import com.qs.pojo.dto.AdminDto;
import com.qs.pojo.dto.CategoryDto;
import com.qs.pojo.entity.Admin;
import com.qs.pojo.entity.Category;
import com.qs.mapper.CategoryMapper;
import com.qs.pojo.entity.User;
import com.qs.response.ResponseEnum;
import com.qs.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-11-12
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public List<Tree<String>> getList(String name) {
        //去除前后空白
        String trimName = null;
        if(!StringUtils.isEmpty(name)){
            trimName = name.trim();
        }
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        /**
         * 根据用户名进行模糊查询
         */
        wrapper.eq(!StringUtils.isBlank(trimName),"name",trimName);
        List<Category> categories = baseMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(categories)) {
            //封装树形结构数据
            List<Tree<String>> treeList = buildTree(categories);
            return treeList;
        }
        return null;
    }

    /**
     * 构造数据结构数据
     * @param categoryList
     * @return
     */
    private List<Tree<String>> buildTree(List<Category> categoryList) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 最大递归深度
        treeNodeConfig.setDeep(2);
        List<Tree<String>> treeNodes = TreeUtil.build(categoryList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId().toString());
                    tree.setParentId(treeNode.getPid().toString());
                    // 扩展属性 ...
                    tree.putExtra("key", treeNode.getId());
                    tree.putExtra("name", treeNode.getName());
                    tree.putExtra("number", treeNode.getNumber());
                });
        return treeNodes;
    }

    @Override
    public void updateByKey(CategoryDto categoryDto) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto,category);
        category.setId(categoryDto.getKey());
        baseMapper.updateById(category);
    }

    @Override
    public CategoryDto echo(Integer id) {
        if(null != id){
            Category category = baseMapper.selectById(id);
            CategoryDto categoryDto = new CategoryDto();
            BeanUtils.copyProperties(category,categoryDto);
            categoryDto.setKey(category.getId());
            return categoryDto;
        }
        return null;
    }

    @Override
    public void saveCategory(Category category) {
        if(null != category.getPid()) {
            //先新增
            baseMapper.insert(category);
            //说明是二级分类
            Category selected = baseMapper.selectById(category.getPid());
            //将一级分类的数量加1
            selected.setNumber(selected.getNumber() + 1);
            baseMapper.updateById(selected);
        }else {
            //说明是一级分类直接新增
            baseMapper.insert(category);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatchByIds(List<Integer> ids) {
        //查询要删除的分类是否是一级分类，如果是一级分类且下面还有二级分类则无法删除
        List<Category> categories = baseMapper.selectBatchIds(ids);
        //过滤出父级分类
        List<Category> pidCategory = categories.stream().filter(category -> category.getPid() == 0).collect(Collectors.toList());
        //查询父级分类下是否还有二级分类
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        pidCategory.stream().forEach(item -> {
            wrapper.eq("pid",item.getId());
            List<Category> list = baseMapper.selectList(wrapper);
            if(!CollectionUtils.isEmpty(list)){
                throw new ServiceException(ResponseEnum.HAVE_CATEGORY);
            }
        });
        //即使父级分类有值，其下肯定没有二级分类了，直接删除即可
        if(!CollectionUtils.isEmpty(pidCategory)){
            baseMapper.deleteBatchIds(ids);
        }else{
            //这些分类全是二级分类
            List<Integer> parentIds = categories.stream().map(Category::getPid).collect(Collectors.toList());
            parentIds.stream().forEach(item -> {
                //根据id查询出父级分类将其修改数量
                Category category = baseMapper.selectOne(new QueryWrapper<Category>().eq("id",item));
                category.setNumber(category.getNumber() - 1);
                baseMapper.updateById(category);
            });
            baseMapper.deleteBatchIds(ids);
        }
    }

    @Override
    public String getCategorys(String categoryName) {
        if(null != categoryName){
            QueryWrapper<Category> wrapper = new QueryWrapper<>();
            wrapper.eq("name",categoryName);
            Category category = baseMapper.selectOne(wrapper);
            if(null != category){
                //父分类
                if(category.getPid().intValue() == StatusConstant.CATEGORY_PARENT){
                    QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("pid",category.getId());
                    List<Category> categories = baseMapper.selectList(queryWrapper);
                    if(!CollectionUtils.isEmpty(categories)){
                        String name = "";
                        for (int i = 0; i < categories.size(); i++) {
                            name += " / " + categories.get(i).getName();
                        }
                        return categoryName + name;
                    }
                    return null;
                }else{
                    //子分类
                    Category selected = baseMapper.selectById(category.getPid());
                    if(null != selected){
                        String name = "";
                        name = selected.getName() + " / " + category.getName();
                        return name;
                    }
                    return null;
                }
            }
            return null;
        }
        return null;
    }
}
